/* eslint-disable no-unused-vars */
/* eslint-disable no-shadow */

const state = {
  client: null,
  msg: undefined,
  msgCount: 0
};

const mutations = {
  SET_MSG(state, data) {
    state.msg = data;
    state.msgCount += 1;
  },
  SET_CLIENT(state, data) {
    state.client = data;
  }
};

const actions = {
  initWS({ commit, dispatch }, data) {
    if (this.client) {
      dispatch("closeWs");
    }
    const client = new Api.WS({
      ...data,
      handleEvent(e) {
        commit("SET_MSG", e.data);
      }
    });
    commit("SET_CLIENT", client);
  },
  sendMsg({ commit, state }, data) {
    try {
      state.client && state.client.send(JSON.stringify(data));
    } catch (error) {
      console.log(error);
    }
  },
  closeWs({ commit, state }, data) {
    try {
      state.client && state.client.close();
    } catch (error) {
      console.log(error);
    }
    commit("SET_CLIENT", null);
  }
};
const getters = {
  msg: state => state.msg,
  msgCount: state => state.msgCount
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
